package com.jerry.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Configuration
public class RestTemplateConfig {
    private final RestTemplateLoggingInterceptor restTemplateLoggingInterceptor;
    private final RestTemplateErrorHandler restTemplateErrorHandler;


    public RestTemplateConfig(RestTemplateLoggingInterceptor restTemplateLoggingInterceptor, RestTemplateErrorHandler restTemplateErrorHandler) {
        this.restTemplateLoggingInterceptor = restTemplateLoggingInterceptor;
        this.restTemplateErrorHandler = restTemplateErrorHandler;
    }
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder,
                                     ClientHttpRequestFactory
                                             httpRequestFactory) {
        RestTemplate restTemplate = builder.build();
        restTemplate.setInterceptors(Collections.singletonList(restTemplateLoggingInterceptor));
        restTemplate.setErrorHandler(restTemplateErrorHandler);
        restTemplate.setRequestFactory(new
                BufferingClientHttpRequestFactory(httpRequestFactory));
        return restTemplate;
    }
    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new
                SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setConnectTimeout(6400000);
        simpleClientHttpRequestFactory.setReadTimeout(640000);
        return simpleClientHttpRequestFactory;
    }
}

